#include "RS232ProtocolPacket.h"

CRS232ProtocolPacket::CRS232ProtocolPacket(void)
{
	for( int i = 0; i < NUMBER_OF_COMMAND_BYTES; i++)
		cCommand[i] = 0;

	for( int i = 0; i < NUMBER_OF_DATA_BYTES; i++)
		cData[i] = 0;
}

void CRS232ProtocolPacket::getCommandBytes(char* ptrCommandBytesBack)
{
	for(int i = 0; i < NUMBER_OF_COMMAND_BYTES; i++)
		ptrCommandBytesBack[i] = cCommand[i];
}

void CRS232ProtocolPacket::getDataBytes(char* ptrDataBytesBack)
{
	for(int i = 0; i < NUMBER_OF_DATA_BYTES; i++)
		ptrDataBytesBack[i] = cData[i];
}

void CRS232ProtocolPacket::setPacket(char* ptrPacketBytes)
{
	for(int i = 0; i < NUMBER_OF_COMMAND_BYTES; i++)
		cCommand[i] = ptrPacketBytes[i];

	for(int i = 0; i < NUMBER_OF_DATA_BYTES; i++)
		cData[i] = ptrPacketBytes[NUMBER_OF_COMMAND_BYTES + i];
}
void CRS232ProtocolPacket::getPacket(char* ptrPacketBytesBack)
{
	for(int i = 0; i < NUMBER_OF_COMMAND_BYTES; i++)
		ptrPacketBytesBack[i] = cCommand[i];

	for(int i = 0; i < NUMBER_OF_DATA_BYTES; i++)
		ptrPacketBytesBack[NUMBER_OF_COMMAND_BYTES + i] = cData[i];
}

Command CRS232ProtocolPacket::DecodeCommand()
{
	int iTmp = 0;

	for( int i = 0; i < NUMBER_OF_COMMAND_BYTES; i++ )
		iTmp |= cCommand[i] << (NUMBER_OF_COMMAND_BYTES - 1 - i) * 8;

	if( iTmp > COMMANDS_START && iTmp < COMMANDS_END )
		return (Command) iTmp;
	else
		return NO_COMMAND;
}
void CRS232ProtocolPacket::EncodeCommand(Command Cmd)
{
	int iValTmp = Cmd;

	for(int i = 0; i < NUMBER_OF_COMMAND_BYTES; i++)
		cCommand[NUMBER_OF_COMMAND_BYTES - 1 - i] = 0xff & ( (char) (iValTmp >> i * 8) );
}
Register CRS232ProtocolPacket::DecodeRegister()
{
	int iTmp = 0;

	for( int i = 0; i < DATA_BYTES_REGISTER_ADDRESS; i++ )
		iTmp |= cData[i] << (DATA_BYTES_REGISTER_ADDRESS - 1 - i) * 8;

	if( iTmp > REGISTER_MIN && iTmp < REGISTER_MAX )
		return (Register) iTmp;
	else
		return NO_REGISTER;
}
void CRS232ProtocolPacket::EncodeRegister(Register Reg)
{
	int iValTmp = Reg;

	for(int i = 0; i < DATA_BYTES_REGISTER_ADDRESS; i++)
		cData[DATA_BYTES_REGISTER_ADDRESS - 1 - i] = 0xff & ( (char) (iValTmp >> i * 8) );
}
int CRS232ProtocolPacket::DecodeRegisterValue()
{
  int iTmp = 0;

  for( int i = 0; i < DATA_BYTES_REGISTER_VALUE; i++ )
    iTmp |= ( ((unsigned int) cData[DATA_BYTES_REGISTER_ADDRESS + i]) & 0x00ff) << ( (DATA_BYTES_REGISTER_VALUE - 1 - i) * 8 );

  return iTmp;
}
void CRS232ProtocolPacket::EncodeRegisterValue(int iVal)
{
	int iValTmp = iVal;

	for(int i = 0; i < DATA_BYTES_REGISTER_VALUE; i++)
		cData[DATA_BYTES_REGISTER_ADDRESS + DATA_BYTES_REGISTER_VALUE - 1 - i] = 0xff & ( (char) (iValTmp >> i * 8) );
}
int CRS232ProtocolPacket::DecodeRegisterBit()
{
  return DecodeRegisterValue();
}
